package com.lpx.controller;

import java.security.Principal;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author ccit
 */
@Controller
@RequestMapping("/page")
public class TestController {
	
	@GetMapping("/hello")
	@ResponseBody
	public String firstMethd() {
		
		return "hello  security!";
	}
	
	@RequestMapping("/index")
	public String index(Principal principal) {
		System.out.println("用户："+principal.getName()+"登陆成功");
		return "index";
	}
	
	@RequestMapping("/logout")
	public String logout() {
		return "login";
	}
	
	//只有当前登录用户名为 javaboy 的用户才可以访问该方法
    @PreAuthorize("principal.username.equals('javaboy')")
    public String hello() {
        return "hello";
    }

    //表示访问该方法的用户必须具备 admin 角色
    @PreAuthorize("hasRole('admin')")
    public String admin() {
        return "admin";
    }

    //表示方法该方法的用户必须具备 user 角色，但是注意 user 角色需要加上 ROLE_ 前缀
    @Secured({"ROLE_teacher","ROLE_student"})
    @GetMapping("/user")
    @ResponseBody
    public String user() {
        return "@Secured";
    }

    //表示访问该方法的 age 参数必须大于 98，否则请求不予通过
    @PreAuthorize("#age>98")
    public String getAge(Integer age) {
        return String.valueOf(age);
    }
	
}
